﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MapMaster : MonoBehaviour {

	public GameMaster GameMaster; 
	public int Level;
	public Player Player;
	public CheckPoint StartPoint;
	public CheckPoint EndPoint;

	public CheckPoint CurrentCheckPoint;

	public static MapMaster Instance;
	
	// Use this for initialization
	void Awake () {
		MapMaster.Instance = this;
		if (GameObject.Find ("GameMaster") == null) {
			GameMaster = (GameMaster) GameObject.Instantiate (GameMaster);
			GameMaster.name = "GameMaster";
		} else {
			GameMaster = GameObject.Find ("GameMaster").GetComponent<GameMaster>();
		}
		GameMaster.OnLevelStart (this.Level);
		this.CurrentCheckPoint = StartPoint;
		Player.transform.position = this.CurrentCheckPoint.transform.position; 
	}

	void Start(){
		SaveGoldBallStutes ();
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	public void KillPlayer(){
		Debug.Log("KillPlayer");
		Player.transform.position = this.CurrentCheckPoint.transform.position;
		GameMaster.OnPlayerDeath ();
		LoadGoldBallStutes ();
	}

	public void Save(CheckPoint checkPoint){
		//set current
		this.CurrentCheckPoint = checkPoint;
		SaveGoldBallStutes ();
		//check level pass
		if (this.CurrentCheckPoint == EndPoint && IsAllGoldBallEaten()) {
			Debug.Log("level completed!!!");
			GameMaster.LoadNextLevel();
		}
	}

	public List<GoldBall> GoldBalls = new List<GoldBall>();
	public void RegisterGoldBall(GoldBall ball){
		GoldBalls.Add (ball);

	}

	public void PlayerEatGoldBall(GoldBall ball){

	}

	public bool IsAllGoldBallEaten(){
		foreach(GoldBall ball in GoldBalls){
			if(ball.gameObject.activeSelf) return false;
		}
		return true;
	}

	public List<bool> GoldBallsStutes = new List<bool>();
	private void SaveGoldBallStutes(){
		GoldBallsStutes.Clear ();
		foreach(GoldBall ball in GoldBalls){
			GoldBallsStutes.Add(ball.gameObject.activeSelf);
		}
	}

	private void LoadGoldBallStutes(){
		int index = GoldBallsStutes.Count;
		for (int i = 0; i < index; i++) {
			bool b = GoldBallsStutes[i];
			GoldBalls[i].gameObject.SetActive(b);
		}
	}
}
